<?php

namespace app\api\model\vipcard;

use app\common\model\vipcard\Order as OrderModel;
use app\api\model\vipcard\Card as CardModel;
use app\api\model\vipcard\OrderPlan as OrderPlanModel;
use app\common\model\Wxapp as WxappModel;
use app\common\service\Order as OrderService;
use app\common\exception\BaseException;
use app\api\model\dealer\Order as DealerOrderModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\User as UserModel;
use app\common\library\MysicLog;
use think\Db;
/**
 * 用户充值订单模型
 * Class Order
 * @package app\api\model\recharge
 */
class Order extends OrderModel
{


    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'wxapp_id',
    ];



    /**
     * 获取订单详情(待付款状态)
     * @param $orderNo
     * @return self|null
     * @throws \think\exception\DbException
     */
    public static function getPayDetail($orderNo)
    {
        return self::detail(['order_no' => $orderNo, 'pay_status' => 10]);
    }


    /**
     * 获取订单详情(待付款状态)
     * @param $orderNo
     * @return self|null
     * @throws \think\exception\DbException
     */
    public static function testGetPayDetail($orderNo)
    {
        return self::detail(['order_no' => $orderNo]);
    }


    /**
     * 表单验证
     * @param $rechargeType
     * @param $planId
     * @param $customMoney
     * @return bool
     */
    private function validateForm($card_id)
    {
        if (empty($card_id)) {
            $this->error = '参数错误';
            return false;
        }
        $cardInfo = Db::name("wxapp_card")->where(['status'=>1,'is_delete'=>0])->find($card_id);

        if (empty($cardInfo)) {
            $this->error = "储值卡不存在，请刷新后重试";
            return false;
        }
        return true;
    }

    /**
     * 创建充值订单
     * @param \app\api\model\User $user 当前用户信息
     * @param int $card_id 套餐id
     * @return bool|false|int
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function createOrder($user,$card_id)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/vipcard');
        // +----------------------------------------------------------------------
        // | 储值预下单开始
        // +----------------------------------------------------------------------
        $log->info('开始', '储值预下单开始');

        // 验证用户输入
        if (!$this->validateForm($card_id)) {
            $log->info($this->error ?: '数据验证错误', '数据验证失败');
            $this->error = $this->error ?: '数据验证错误';
            return false;
        }

        try {
            $data = $this->getOrderData($user,$card_id);
            $orderResult = $this->saveOrder($data);
            $log->info($orderResult, '生成订单状态');
            return true;
        } catch(\Exception $e) {
            $log->info(exceptionLogFormat($e), '生成订单失败');
            $this->error = "出了点问题，请重新下单";
            return false;
        }

    }


    /**
     * 生成充值订单
     * @param $user
     * @param $rechargeType
     * @param $planId
     * @param $customMoney
     * @return array
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function getOrderData($user,$card_id)
    {
        // 订单信息
        $data = [
            'order' => [
                'user_id' => $user['user_id'],
                'order_no' => 'VIP' . OrderService::createOrderNo(),
                'wxapp_id' => self::$wxapp_id,
            ],
            'plan' => []    // 订单套餐快照
        ];

        // 获取订单金额
        $this->createDataByPlan($data, $card_id);
        return $data;
    }

    /**
     * 保存订单记录
     * @param $data
     * @return bool|false|int
     */
    private function saveOrder($data)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/vipcard');
        // +----------------------------------------------------------------------
        // | 订单表数据---order表
        // +----------------------------------------------------------------------
        $log->info($data['order'], '订单表数据');
        // +----------------------------------------------------------------------
        // | 订单快照表数据----wxapp_card_order_plan表
        // +----------------------------------------------------------------------
        $log->info($data['plan']->toarray(), '订单快照表数据');
        // 写入订单记录
        $this->isUpdate(false)->save($data['order']);
        $log->info($this['order_id'], '订单ID');
        // 记录订单套餐快照
        if (!empty($data['plan'])) {
            $PlanModel = new OrderPlanModel;
            return $PlanModel->add($this['order_id'], $data['plan']);
        }
        return true;
    }




    /**
     * 创建充值订单数据
     * @param $order
     * @param $planId
     * @return bool
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function createDataByPlan(&$order, $card_id)
    {

        // 获取套餐详情
        $cardInfo = CardModel::detail($card_id);
        if (empty($cardInfo)) {
            throw new BaseException(['msg' => '储值卡不存在，请刷新后重试']);
        }

        $order['plan'] = $cardInfo;
        $order['order']['total_price'] = $cardInfo['card_real_money'];//商品总金额(不含优惠折扣)
        $order['order']['order_price'] = $cardInfo['card_real_money'];//订单金额(含优惠折扣)
        $order['order']['pay_price'] = $cardInfo['card_real_money'];//实际付款金额(包含运费)
        $order['order']['pay_price'] = $cardInfo['card_real_money'];//实际付款金额(包含运费)
        $order['order']['pay_type'] = 20;//支付方式(10余额支付 20微信支付)
        $order['order']['pay_status'] = 10;//付款状态(10未付款 20已付款)
        $order['order']['pay_status'] = 10;//付款状态(10未付款 20已付款)
        $order['order']['delivery_type'] = 10;//配送方式(10快递配送 20上门自提)
        $order['order']['order_source'] = 40;//10普通订单 20砍价订单 30秒杀订单 40会员充值订单
        $order['order']['is_fictitious'] = 1;//是否为虚拟物品 1 是 2 不是

        return true;
    }

    /**
     * 创建自定义充值订单数据
     * @param $order
     * @param $customMoney
     * @return bool
     */
    private function createDataByCustom(&$order, $customMoney)
    {
        // 用户支付金额
        $order['order']['pay_price'] = $customMoney;
        // 充值设置
        $setting = SettingModel::getItem('recharge');
        if ($setting['is_custom'] == false) {
            return true;
        }
        // 根据自定义充值金额匹配满足的套餐
        if ($setting['is_match_plan'] == true) {
            $matchPlanInfo = (new PlanModel)->getMatchPlan($customMoney);
            if (!empty($matchPlanInfo)) {
                $order['plan'] = $matchPlanInfo;
                $order['order']['plan_id'] = $matchPlanInfo['plan_id'];
                $order['order']['gift_money'] = $matchPlanInfo['gift_money'];
            }
        }
        return true;
    }



    /**
     * 检测支付密码
     * @param null $passwprd
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function validatePass($user,$password)
    {

        if(!$user['pay_password']){
            $this->error = '请先设置支付密码';
            return false;
        }
        if(empty($password)){
            $this->error = '请输入支付密码';
            return false;
        }
        if($user['pay_password']!=yoshop_hash($password)){
            $this->error = '支付密码错误';
            return false;
        }
        return true;
    }

}